package com.abner.juc;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * 分支合并框架
 * @author Abner
 */
public class ForkJoinDemo {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        MyTask myTask = new MyTask(1, 100);
        ForkJoinPool threadPool = new ForkJoinPool();
        ForkJoinTask<Integer> submit = threadPool.submit(myTask);
        System.out.println(submit.get());
        threadPool.shutdown();
    }
}


class MyTask extends RecursiveTask<Integer> {

    private static final Integer ADJUST_VALUE = 10;
    private int begin;
    private int end;
    private int res;

    public MyTask(int begin, int end) {
        this.begin = begin;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        if((end - begin) < ADJUST_VALUE) {
            for (int i = begin; i <= end; i++) {
                res = res + i;
            }
        }else {
            int middle = (end + begin) / 2;
            MyTask myTask1 = new MyTask(begin, middle);
            MyTask myTask2 = new MyTask(middle + 1, end);
            // 执行子任务
            myTask1.fork();
            myTask2.fork();
            //合并子任务
            res = myTask1.join() + myTask2.join();
        }
        return res;
    }
}